package com.web.controller.api;

import com.web.annotation.UserAccess;
import com.web.config.BaseReqConfig;
import com.web.config.KftPayCommConfig;
import com.web.config.KppAppPayConfiguration;
import com.web.config.PayConfiguration;
import com.web.dao.*;
import com.web.domain.ApiResponse;
import com.web.dto.OnlineOrderDto;
import com.web.entity.*;
import com.web.kftsdk.api.KftPayConfigStorage;
import com.web.kftsdk.api.KftPayService;
import com.web.kftsdk.common.bean.PayRes;
import com.web.kftsdk.entity.KppAppPayReq;
import com.web.kftsdk.entity.SplitInfo;
import com.web.klock.annotation.Klock;
import com.web.manager.CoreManager;
import com.web.manager.jpush.SendJPushMessage;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.web.pay.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.math.BigDecimal.ROUND_HALF_DOWN;

/**
 * @author FDjavaone
 * @date 2017/9/5
 */

@Slf4j
@RestController
@RequestMapping("api")
@Transactional(rollbackFor = Exception.class)
public class ConsumeOrderController {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private PlatformMapper platformMapper;
    @Autowired
    private ProfitConfigMapper profitConfigMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private ProfitDetailMapper profitDetailMapper;
    @Autowired
    private MerchantDetailMapper merchantDetailMapper;
    @Autowired
    private PoundageConfigMapper poundageConfigMapper;
    @Autowired
    private ConsumptionDetailMapper consumptionDetailMapper;
    @Autowired
    private PayConfiguration payConfiguration;
    @Autowired
    private RegionRecordMapper regionRecordMapper;
    @Autowired
    private CoreManager coreManager;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private KftApplyMapper kftApplyMapper;
    @Autowired
    private  KppAppPayConfiguration kppAppPayConfiguration;
    @Autowired
    private KftPayCommConfig kftPayCommConfig;
    @Autowired
    private BaseReqConfig baseReqConfig;

    /**
     * 线上订单创建
     */
    @UserAccess
    @Klock(keys = {"#onlineOrderDto.storeId"})
    @RequestMapping("/app/online/onlineOrderCreate")
    public ApiResponse onlineOrderCreate(OnlineOrderDto onlineOrderDto, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse apiResponse = new ApiResponse();
        Date date = new Date();
        //支付类型1分润账户支付2消费账户支付3商户货款账户支付4支付宝支付5微信支付
        //创建订单
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderNum = "";
        //消费者账户信息
        Account account = accountMapper.selectByMid(onlineOrderDto.getmId());
        //消费者信息
        Member member = memberMapper.selectByPrimaryKey(onlineOrderDto.getmId());

        if (member.getAuthStatus() == 0) {
            apiResponse.setStatus(900123);
            apiResponse.setMessage("用户未实名不能创建订单并支付！");
            return apiResponse;
        }

        //商家店铺信息
        Store store = storeMapper.selectByPrimaryKey(onlineOrderDto.getStoreId());

        if (store.getmId().equals(member.getId())) {
            apiResponse.setStatus(900801);
            apiResponse.setMessage("本人不能在自己的店铺里面消费");
            return apiResponse;
        }

        //店铺让利比例，小数
        BigDecimal merchantProfitPercent = new BigDecimal(new Double(store.getLevel()) * 10).divide(new BigDecimal("100"), 2, ROUND_HALF_DOWN);

        orderNum += sdf.format(date) + date.getTime();
        Order order = new Order();
        order.setmId(onlineOrderDto.getmId());
        order.setStoreId(onlineOrderDto.getStoreId());
        order.setStatus(0);
        order.setAddress(onlineOrderDto.getAddress());
        order.setName(onlineOrderDto.getName());
        order.setOrderNum(orderNum);
        order.setOrderType("online");
        order.setPhone(onlineOrderDto.getPhone());
        order.setTipPrice(onlineOrderDto.getTipPrice());
        order.setTotalPrice(onlineOrderDto.getTotalPrice());
        order.setModifyTime(date);
        order.setCreateTime(date);
        BigDecimal totalPrice = new BigDecimal(0);
        //创建订单下面的商品明细
        List<OrderGoods> orderGoods = new ArrayList<>();
        String[] goodsArr = onlineOrderDto.getGoods().split("\\|");
        try {
            for (int i = 0; i < goodsArr.length; i++) {
                OrderGoods orderGood = new OrderGoods();
                Goods goods = goodsMapper.selectByPrimaryKey(new Long(goodsArr[i].split("-")[0]));
                if (goods.getNum() < new Integer(goodsArr[i].split("-")[1])) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new RuntimeException("商品" + goods.getTitle() + "库存不足！");
                }
                goods.setNum(goods.getNum() - new Integer(goodsArr[i].split("-")[1]));
                goods.setModifyTime(date);
                //修改库存
                goodsMapper.updateByPrimaryKeySelective(goods);
                totalPrice = totalPrice.add(goods.getPrice().multiply(new BigDecimal(goodsArr[i].split("-")[1])));
                orderGood.setCreateTime(date);
                orderGood.setModifyTime(date);
                orderGood.setGoodId(goods.getId());
                orderGood.setNum(new Integer(goodsArr[i].split("-")[1]));
                orderGood.setPrice(goods.getPrice());
                orderGood.setTitle(goods.getTitle());
                orderGood.setImage(goods.getImage());
                orderGoods.add(orderGood);
            }
            if (totalPrice.compareTo(onlineOrderDto.getTotalPrice()) != 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new RuntimeException("订单商品总价格异常！");
            }
            order.setTotalPrice(totalPrice);

            //金额的计算为消费金额加上小费金额
            totalPrice = totalPrice.add(onlineOrderDto.getTipPrice());
            //商户总的让利金额
            BigDecimal merchantTransfer = totalPrice.multiply(merchantProfitPercent).setScale(2, ROUND_HALF_DOWN);
            order.setTransferPrice(merchantTransfer);
            //生成订单
            orderMapper.insertSelective(order);

            Message message = new Message();
            message.setTargetName("");
            message.setTarget(store.getmId());
            message.setFromName("系统");
            message.setFrom(0L);
            message.setTitle("新订单提醒");
            message.setContent("您有新的订单产生请及时处理，订单编号：" + orderNum);
            message.setCreateTime(date);
            message.setModifyTime(date);


            //生成订单商品明细
            for (OrderGoods o : orderGoods) {
                o.setOrderId(order.getId());
                orderGoodsMapper.insertSelective(o);
            }
            if (onlineOrderDto.getType() == 1) {
                //分润账户支付


                // 用户分润账户金额减少、用户的推荐人（如果有）及推荐人的推荐人（如果有）的分润账户各增加商户让利的 x%，
                // 前提是上线的等级比该用户高、对应店铺商家用户的的推荐人（如果有）及推荐人的推荐人（如果有）的分润账户各增加商户让利的 x%，
                // 前提是上线的等级比该用户高、累积用户和用户的上级和上级的上级的团队总消费，并判断用户是否能升级、累积用户上级和上级的上级
                // 的累积奖金、累积商户的上级和上级的上级的累积奖金、
                // (根据商户的归属省市区，向对应省市区代理商发放对应比例的收益提成、)
                // 公司市场资金池、公司资金池、用户睿积分账户增加配置的相应比例的金额、奖金分配池按照实际上获得收益的人的收益的金额累积、分配完剩余
                // 金额累积到公司利润账户、
                // 用户的所有睿积分自动生成挂买单向公司的msk账户购买msk，
                // 如果该用户的上级是原积分用户，且用户的原积分不为零，
                // 那么该用户的原积分相当于msk卖出对应数量，此时注意如果剩余的原积分已经不足将全部卖给公司msk账户，钱从市场资金池支付给原积分用户
                // ，原积分用户得到的收益手续费部分累积到公司利润账户，剩余部分按设置的比例累积到用户的分润账户和消费账户，
                if (account.getProfit().compareTo(totalPrice) < 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new RuntimeException("分润账户余额不足！");
                }
                //用户分润账户资金减少
                accountMapper.profitSubtract(totalPrice, account.getId());
                ProfitDetail profitDetail = new ProfitDetail();
                profitDetail.setModifyTime(date);
                profitDetail.setCreateTime(date);
                profitDetail.setContent("订单" + orderNum + "消费支出");
                profitDetail.setDetail("-" + totalPrice);
                profitDetail.setaId(account.getId());
                profitDetail.setBal(accountMapper.selectByPrimaryKey(account.getId()).getProfit().toString());
                profitDetail.setFromNum(orderNum);
                profitDetail.setName(member.getName());
                profitDetail.setPhone(member.getPhone());
                profitDetailMapper.insertSelective(profitDetail);

                //企业订单
                //更新订单支付状态
                Order update = new Order();
                update.setPayType(1);
                update.setStatus(1);
                update.setId(order.getId());
                orderMapper.updateByPrimaryKeySelective(update);
                messageMapper.insertSelective(message);
                SendJPushMessage.jPushByMessage(message);
                apiResponse.setStatus(900000);
                apiResponse.setMessage("支付成功");
                return apiResponse;

            } else if (onlineOrderDto.getType() == 2) {
                //消费账户支付
                if (account.getConsumption().compareTo(totalPrice) < 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new RuntimeException("消费账户余额不足！");
                }
                //用户消费账户资金减少
                accountMapper.consumptionSubtract(totalPrice, account.getId());
                ConsumptionDetail consumptionDetail = new ConsumptionDetail();
                consumptionDetail.setModifyTime(date);
                consumptionDetail.setCreateTime(date);
                consumptionDetail.setContent("订单" + orderNum + "消费支出");
                consumptionDetail.setDetail("-" + totalPrice);
                consumptionDetail.setBal(accountMapper.selectByMid(account.getmId()).getConsumption().toString());
                consumptionDetail.setFromNum(orderNum);
                consumptionDetail.setName(member.getName());
                consumptionDetail.setPhone(member.getPhone());
                consumptionDetail.setaId(account.getId());
                consumptionDetailMapper.insertSelective(consumptionDetail);
                //企业订单 更新订单支付状态
                Order update = new Order();
                update.setPayType(3);
                update.setStatus(1);
                update.setId(order.getId());
                orderMapper.updateByPrimaryKeySelective(update);
                messageMapper.insertSelective(message);
                SendJPushMessage.jPushByMessage(message);
                apiResponse.setStatus(900000);
                apiResponse.setMessage("支付成功");
                return apiResponse;
            } else if (onlineOrderDto.getType() == 3) {
                //商户货款支付
                if (account.getMerchantPayment().compareTo(totalPrice) < 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new RuntimeException("商户货款余额不足！");
                }
                Store memberStore = storeMapper.selectByMid(member.getId());
                //用户商户货款资金减少
                accountMapper.merchantPaymentSubtract(totalPrice, account.getId());
                MerchantDetail merchantDetail = new MerchantDetail();
                merchantDetail.setModifyTime(date);
                merchantDetail.setCreateTime(date);
                merchantDetail.setContent("订单" + orderNum + "消费支出");
                merchantDetail.setDetail("-" + totalPrice);
                merchantDetail.setaId(account.getId());
                merchantDetail.setBal(accountMapper.selectByPrimaryKey(account.getId()).getMerchantPayment().toString());
                merchantDetail.setName(member.getName());
                merchantDetail.setPhone(member.getPhone());
                merchantDetail.setFromNum(orderNum);
                merchantDetail.setConsumer(member.getName());
                merchantDetail.setConsumerId(member.getId());
                if (memberStore != null) {
                    merchantDetail.setStore(memberStore.getMerchantName());
                    merchantDetail.setStoreId(memberStore.getId());
                }

                merchantDetail.setType(2);
                merchantDetail.setTotalBal(accountMapper.countMerchantNum().toString());
                merchantDetailMapper.insertSelective(merchantDetail);

                //企业订单
                //更新订单支付状态
                Order update = new Order();
                update.setPayType(2);
                update.setStatus(1);
                update.setId(order.getId());
                orderMapper.updateByPrimaryKeySelective(update);
                messageMapper.insertSelective(message);
                SendJPushMessage.jPushByMessage(message);
                apiResponse.setStatus(900000);
                apiResponse.setMessage("支付成功");
                return apiResponse;

            } else if (onlineOrderDto.getType() == 4) {
                try {
                    //支付宝支付订单创建
                    AliPayDto aliPayDto = new AliPayDto();
                    aliPayDto.setPayAppid(payConfiguration.getAli().getAppid());
                    aliPayDto.setPayUrl(payConfiguration.getAli().getUrl());
                    aliPayDto.setPaySelfSecret(payConfiguration.getAli().getSelfSecret());
                    aliPayDto.setPayPublicSecret(payConfiguration.getAli().getPublicSecret());
                    aliPayDto.setPayPublicSecret2(payConfiguration.getAli().getPublicSecret2());
                    //3分钟不支付，交易结束
                    aliPayDto.setTimeOutExpress("3m");
                    aliPayDto.setOutTradeNo(orderNum);
                    aliPayDto.setSubject("在线消费");
                    //测试0.01元 支付宝 单位元
                    aliPayDto.setTotalAmount(String.valueOf(totalPrice));
                    aliPayDto.setBody("消费支付总额" + totalPrice);
                    aliPayDto.setNotifyUrl(payConfiguration.getAli().getCallback() + "/api/open/ali_notify");
                    PayResponse aliResponse = AliPayManage.mg.aliPayApp(aliPayDto);
                    return aliResultDeal(aliResponse);
                } catch (Exception e) {
                    e.printStackTrace();
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new RuntimeException("支付宝支付订单创建失败！");
                }
            } else if (onlineOrderDto.getType() == 5) {
                return wxResultDeal(payConfiguration,totalPrice,orderNum);
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new RuntimeException("未知的支付方式！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            apiResponse.setMessage(e.getMessage());
            apiResponse.setStatus(900801);
        }
        return apiResponse;
    }

    /**
     * 直接消费订单创建
     */
    @UserAccess
    @Klock(keys = {"#onlineOrderDto.storeId"})
    @RequestMapping("/app/online/outlineOrderCreate")
    public ApiResponse outlineOrderCreate(OnlineOrderDto onlineOrderDto, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse apiResponse = new ApiResponse();
        Date date = new Date();
        //支付类型1分润账户支付2消费账户支付3商户货款账户支付4支付宝支付5微信支付
        //创建订单
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderNum = "";
        //消费者账户信息
        Account account = accountMapper.selectByMid(onlineOrderDto.getmId());
        //消费者信息
        Member member = memberMapper.selectByPrimaryKey(onlineOrderDto.getmId());


        if (member.getAuthStatus() == 0) {
            apiResponse.setStatus(900123);
            apiResponse.setMessage("用户未实名不能创建订单并支付！");
            return apiResponse;
        }


        //商家店铺信息
        Store store = storeMapper.selectByPrimaryKey(onlineOrderDto.getStoreId());
        if (store.getmId().equals(member.getId())) {
            apiResponse.setMessage("本人不能在自己的店铺里面消费");
            apiResponse.setStatus(900801);
            return apiResponse;
        }

        //商家账户信息
        Account merchantAccount = accountMapper.selectByMid(store.getmId());
        //商户信息
        Member merchant = memberMapper.selectByPrimaryKey(store.getmId());

        Member memberUp = null;
        if (member.getInvitedCode() != null) {
            //用户上线
            memberUp = memberMapper.selectMyUp(member.getInvitedCode());
        }

        Member merchantUp = null;
        if (merchant.getInvitedCode() != null) {
            //商户上线
            merchantUp = memberMapper.selectMyUp(merchant.getInvitedCode());
        }

        //店铺让利比例，小数
        BigDecimal merchantProfitPercent = new BigDecimal(new Double(store.getLevel()) * 10).divide(new BigDecimal("100"), 2, ROUND_HALF_DOWN);


        //店铺的省市区三级代理商获取
        RegionRecord province = regionRecordMapper.selectProvince(store.getProvince());
        RegionRecord city = regionRecordMapper.selectProvinceAndCity(store.getProvince(), store.getCity());
        RegionRecord region = regionRecordMapper.selectProvinceAndCityAndRegion(store.getProvince(), store.getCity(), store.getRegion());

        //总的奖励分配
        BigDecimal totalBonus = new BigDecimal(0);

        //利润分配配置
        ProfitConfig config = profitConfigMapper.selectByPrimaryKey(1L);
        //msk卖出配置
        PoundageConfig poundageConfig = poundageConfigMapper.selectByPrimaryKey(1L);
        //平台账户信息
        Platform platform = platformMapper.selectByPrimaryKey(1L);


        orderNum += sdf.format(date) + date.getTime();

        Order order = new Order();
        order.setmId(onlineOrderDto.getmId());
        order.setStoreId(onlineOrderDto.getStoreId());
        order.setStatus(0);
        order.setAddress(onlineOrderDto.getAddress());
        order.setName(onlineOrderDto.getName());
        order.setOrderNum(orderNum);
        order.setOrderType("outline");
        order.setPhone(onlineOrderDto.getPhone());
        order.setTipPrice(onlineOrderDto.getTipPrice());
        order.setTotalPrice(onlineOrderDto.getTotalPrice());
        order.setModifyTime(date);
        order.setCreateTime(date);
        BigDecimal totalPrice = onlineOrderDto.getTotalPrice();

        try {
            //金额的计算为消费金额加上小费金额
            totalPrice = totalPrice.add(onlineOrderDto.getTipPrice());
            //商户总的让利金额
            BigDecimal merchantTransfer = totalPrice.multiply(merchantProfitPercent).setScale(2, ROUND_HALF_DOWN);
            order.setTransferPrice(merchantTransfer);
            //生成订单
            orderMapper.insertSelective(order);

            CompanyReport companyReport = new CompanyReport();

            Message message = new Message();
            message.setTargetName("");
            message.setTarget(store.getmId());
            message.setFromName("系统");
            message.setFrom(0L);
            message.setTitle("新订单提醒");
            message.setContent("您有新的订单产生请及时处理，订单编号：" + orderNum);
            message.setCreateTime(date);
            message.setModifyTime(date);


            if (onlineOrderDto.getType() == 1) {
                //分润账户支付
                companyReport.setReserve1("分润消费,订单编号" + orderNum);
                companyReport.setReserve2("1");


                // 用户分润账户金额减少、用户的推荐人（如果有）及推荐人的推荐人（如果有）的分润账户各增加商户让利的 x%，
                // 前提是上线的等级比该用户高、对应店铺商家用户的的推荐人（如果有）及推荐人的推荐人（如果有）的分润账户各增加商户让利的 x%，
                // 前提是上线的等级比该用户高、累积用户和用户的上级和上级的上级的团队总消费，并判断用户是否能升级、累积用户上级和上级的上级
                // 的累积奖金、累积商户的上级和上级的上级的累积奖金、
                //
                // (根据商户的归属省市区，向对应省市区代理商发放对应比例的收益提成、)


                // 公司市场资金池、公司资金池、用户睿积分账户增加配置的相应比例的金额、奖金分配池按照实际上获得收益的人的收益的金额累积、分配完剩余
                // 金额累积到公司利润账户、
                //
                // 用户的所有睿积分自动生成挂买单向公司的msk账户购买msk，
                //
                //
                // 如果该用户的上级是原积分用户，且用户的原积分不为零，
                // 那么该用户的原积分相当于msk卖出对应数量，此时注意如果剩余的原积分已经不足将全部卖给公司msk账户，钱从市场资金池支付给原积分用户
                // ，原积分用户得到的收益手续费部分累积到公司利润账户，剩余部分按设置的比例累积到用户的分润账户和消费账户，
                if (account.getProfit().compareTo(totalPrice) < 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new RuntimeException("分润账户余额不足！");
                }
                //用户分润账户资金减少
                accountMapper.profitSubtract(totalPrice, account.getId());
                ProfitDetail profitDetail = new ProfitDetail();
                profitDetail.setModifyTime(date);
                profitDetail.setCreateTime(date);
                profitDetail.setContent("订单" + orderNum + "消费支出");
                profitDetail.setDetail("-" + totalPrice);
                profitDetail.setaId(account.getId());
                profitDetail.setBal(accountMapper.selectByPrimaryKey(account.getId()).getProfit().toString());
                profitDetail.setFromNum(orderNum);
                profitDetail.setName(member.getName());
                profitDetail.setPhone(member.getPhone());
                profitDetailMapper.insertSelective(profitDetail);


                //核心处理方法
                coreManager.coreOperation(order, totalPrice, totalBonus, merchantTransfer, config, poundageConfig, platform, member, memberUp, account, merchant, merchantUp
                        , merchantAccount, province, city, region, date, store, companyReport);

                messageMapper.insertSelective(message);
                SendJPushMessage.jPushByMessage(message);
                apiResponse.setStatus(900000);
                apiResponse.setMessage("支付成功");
                return apiResponse;

            } else if (onlineOrderDto.getType() == 2) {
                //消费账户支付
                companyReport.setReserve1("基数消费,订单编号" + orderNum);
                companyReport.setReserve2("3");

                if (account.getConsumption().compareTo(totalPrice) < 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new RuntimeException("消费账户余额不足！");
                }
                //用户消费账户资金减少
                accountMapper.consumptionSubtract(totalPrice, account.getId());
                ConsumptionDetail consumptionDetail = new ConsumptionDetail();
                consumptionDetail.setModifyTime(date);
                consumptionDetail.setCreateTime(date);
                consumptionDetail.setContent("订单" + orderNum + "消费支出");
                consumptionDetail.setDetail("-" + totalPrice);
                consumptionDetail.setaId(account.getId());
                consumptionDetail.setBal(accountMapper.selectByMid(account.getmId()).getConsumption().toString());
                consumptionDetail.setFromNum(orderNum);
                consumptionDetail.setName(member.getName());
                consumptionDetail.setPhone(member.getPhone());
                consumptionDetailMapper.insertSelective(consumptionDetail);


                //核心处理方法
                coreManager.coreOperation(order, totalPrice, totalBonus, merchantTransfer, config, poundageConfig, platform, member, memberUp, account, merchant, merchantUp
                        , merchantAccount, province, city, region, date, store, companyReport);

                messageMapper.insertSelective(message);
                SendJPushMessage.jPushByMessage(message);
                apiResponse.setStatus(900000);
                apiResponse.setMessage("支付成功");
                return apiResponse;
            } else if (onlineOrderDto.getType() == 3) {
                //商户货款支付
                companyReport.setReserve1("货款消费,订单编号" + orderNum);
                companyReport.setReserve2("2");

                if (account.getMerchantPayment().compareTo(totalPrice) < 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new RuntimeException("商户货款余额不足！");
                }
                Store memberStore = storeMapper.selectByMid(member.getId());
                //用户商户货款资金减少
                accountMapper.merchantPaymentSubtract(totalPrice, account.getId());
                MerchantDetail merchantDetail = new MerchantDetail();
                merchantDetail.setModifyTime(date);
                merchantDetail.setCreateTime(date);
                merchantDetail.setContent("订单" + orderNum + "消费支出");
                merchantDetail.setDetail("-" + totalPrice);
                merchantDetail.setaId(account.getId());
                merchantDetail.setBal(accountMapper.selectByPrimaryKey(account.getId()).getMerchantPayment().toString());
                merchantDetail.setName(member.getName());
                merchantDetail.setPhone(member.getPhone());
                merchantDetail.setFromNum(orderNum);
                merchantDetail.setConsumer(member.getName());
                merchantDetail.setConsumerId(member.getId());
                if (memberStore != null) {
                    merchantDetail.setStore(memberStore.getMerchantName());
                    merchantDetail.setStoreId(memberStore.getId());
                }

                merchantDetail.setType(2);
                merchantDetail.setTotalBal(accountMapper.countMerchantNum().toString());
                merchantDetailMapper.insertSelective(merchantDetail);

                //核心处理方法
                coreManager.coreOperation(order, totalPrice, totalBonus, merchantTransfer, config, poundageConfig, platform, member, memberUp, account, merchant, merchantUp
                        , merchantAccount, province, city, region, date, store, companyReport);

                messageMapper.insertSelective(message);
                SendJPushMessage.jPushByMessage(message);
                apiResponse.setStatus(900000);
                apiResponse.setMessage("支付成功");
                return apiResponse;

            } else if (onlineOrderDto.getType() == 4) {
                if(onlineOrderDto.getFlag()==null || "".equals( onlineOrderDto.getFlag() )) {
                    //走支付宝支付
                    try {
                        //支付宝支付订单创建
                        AliPayDto aliPayDto = new AliPayDto();
                        aliPayDto.setPayAppid( payConfiguration.getAli().getAppid() );
                        aliPayDto.setPayUrl( payConfiguration.getAli().getUrl() );
                        aliPayDto.setPaySelfSecret( payConfiguration.getAli().getSelfSecret() );
                        aliPayDto.setPayPublicSecret( payConfiguration.getAli().getPublicSecret() );
                        aliPayDto.setPayPublicSecret2( payConfiguration.getAli().getPublicSecret2() );
                        //3分钟不支付，交易结束
                        aliPayDto.setTimeOutExpress( "3m" );
                        aliPayDto.setOutTradeNo( orderNum );
                        aliPayDto.setSubject( "线下消费" );
                        //测试0.01元 支付宝 单位元
                        aliPayDto.setTotalAmount( String.valueOf( totalPrice ) );
                        aliPayDto.setBody( "线下消费支付总额" + totalPrice );
                        aliPayDto.setNotifyUrl( payConfiguration.getAli().getCallback() + "/api/open/ali_notify" );
                        PayResponse aliResponse = AliPayManage.mg.aliPayApp( aliPayDto );
                        return aliResultDeal( aliResponse );


                    } catch (Exception e) {
                        e.printStackTrace();
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        throw new RuntimeException( "支付宝支付订单创建失败！" );
                    }
                }else if("new".equals( onlineOrderDto.getFlag() )){
                    //走快付通app支付

                }

            } else if (onlineOrderDto.getType() == 5) {
                if(onlineOrderDto.getFlag() == null || "".equals(onlineOrderDto.getFlag() )){
                    //采用原来的微信支付方式
                    return wxResultDeal(payConfiguration,totalPrice,orderNum);
                }else if("new".equals( onlineOrderDto.getFlag() )){
                            //再判断该线上订单对应的商家是否成功注册第三方支付二级商户
                        if(kftApplyMapper.findByMid( store.getmId()).getStatus()==2){
                            //已成功申请快付通,用快付通app支付方式
                            KftPayConfigStorage kftPayConfigStorage = new KftPayConfigStorage();
                            kftPayConfigStorage.setPackPath(kftPayCommConfig.getPackPath());
                            kftPayConfigStorage.setSftpPath(kftPayCommConfig.getSftpPath());
                            kftPayConfigStorage.setSftpHost(kftPayCommConfig.getSftpHost());
                            kftPayConfigStorage.setSftpUsername(kftPayCommConfig.getSftpUsername());
                            kftPayConfigStorage.setSftpPassword(kftPayCommConfig.getSftpPassword());
                            kftPayConfigStorage.setKeyPrivate(kftPayCommConfig.getKeyPrivate());
                            kftPayConfigStorage.setDevGateWay(kftPayCommConfig.getDevGateWay());
                            kftPayConfigStorage.setGateWay(kftPayCommConfig.getGateWay());
                            kftPayConfigStorage.init();
                            KftPayService kftPayService = new KftPayService(kftPayConfigStorage);
                            KppAppPayReq kppAppPayReq = new KppAppPayReq();
                            kppAppPayReq.setReqNo(String.valueOf(System.currentTimeMillis()) );
                            kppAppPayReq.setService("kpp_app_pay");
                            kppAppPayReq.setVersion(baseReqConfig.getVersion());
                            kppAppPayReq.setCharset(baseReqConfig.getCharset());
                            kppAppPayReq.setLanguage(baseReqConfig.getLanguage());

                            kppAppPayReq.setMerchantId(kppAppPayConfiguration.getMerchantId());
                            kppAppPayReq.setSecMerchantId(kftApplyMapper.findByMid( store.getmId() ).getKftId() );
                            kppAppPayReq.setOrderNo( orderNum );
                            kppAppPayReq.setTerminalIp(kftPayConfigStorage.getSftpHost());
                            kppAppPayReq.setNotifyUrl( kppAppPayConfiguration.getCallback()+"/api/open/kft_notify");
                            kppAppPayReq.setProductId( onlineOrderDto.getProductId());
                            kppAppPayReq.setAmount(totalPrice.toString());
                            kppAppPayReq.setCurrency( kppAppPayConfiguration.getCurrency() );
                            kppAppPayReq.setTradeName( onlineOrderDto.getTradeName() );
                            kppAppPayReq.setRemark( onlineOrderDto.getRemark() );
                            kppAppPayReq.setTradeTime( order.getCreateTime().toString() );
                            kppAppPayReq.setSubAppId(store.getmId().toString());
                            kppAppPayReq.setBankNo( kppAppPayConfiguration.getBankNo() );
                            kppAppPayReq.setIsS0( kppAppPayConfiguration.getIsS0() );
                            kppAppPayReq.setIsGuarantee( kppAppPayConfiguration.getIsGuarantee() );
                            kppAppPayReq.setIsSplit( kppAppPayConfiguration.getIsSplit() );
                            //分账
                            List<SplitInfo> list = new ArrayList<>();
                            SplitInfo splitInfo = new SplitInfo();
                            splitInfo.setAmount(merchantTransfer.toString() );
                            splitInfo.setMerchantId(kppAppPayConfiguration.getMerchantId());
                            splitInfo.setRemark( kppAppPayConfiguration.getRemark() );
                            list.add(splitInfo);
                            SplitInfo splitInfo2 = new SplitInfo();
                            splitInfo2.setAmount((totalPrice.subtract( merchantTransfer )).toString());
                            splitInfo2.setMerchantId( kftApplyMapper.findByMid( store.getmId() ).getKftId());
                            splitInfo2.setRemark( onlineOrderDto.getRemark());
                            list.add( splitInfo2 );
                            JSONObject object = JSONObject.fromObject( list );
                            kppAppPayReq.setSplitInfo( object.toString());
                            //给所有需要参与签名的请求参数加签后得出的字符串
                            Map<String,String> map = kppAppPayReq.toMap( "kpp_app_pay" );
                             Map<String,String> signMap =  kftPayService.createSign(map);
                            String signatureInfo = signMap.get( "signatureInfo" );
                            kppAppPayReq.setSignatureInfo( signatureInfo );
                            kppAppPayReq.setSignatureAlgorithm(baseReqConfig.getSignatureAlgorithm());
                            PayRes res = kftPayService.kppAppPay(kppAppPayReq);
                            if(res.valid()){
                              return  ApiResponse.custom().ok("快付通请求成功").addParams(res.getData());
                            }else{
                                return ApiResponse.custom().failure("快付通请求失败");
                            }

                        }else{
                            //线上订单对应的的商家未成功注册第三方支付二级商户,仍使用原来的微信支付
                            return wxResultDeal(payConfiguration,totalPrice,orderNum);

                        }
            }
                } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new RuntimeException("未知的支付方式！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            apiResponse.setMessage(e.getMessage());
            apiResponse.setStatus(900801);
        }
        return apiResponse;
    }

    private static ApiResponse aliResultDeal(PayResponse payResponse){
        ApiResponse response=new ApiResponse();
        if (payResponse.getStatus() == 1) {
            response.setStatus(900000);
            response.setMessage(payResponse.getMessage());
            response.setParams(payResponse.getParams());
            return response;
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException("支付宝支付订单创建失败！");
        }
    }

    private static ApiResponse wxResultDeal(PayConfiguration payConfiguration,BigDecimal totalPrice,String orderNum){
        ApiResponse apiResponse=new ApiResponse();
        try {
            //微信支付
            WxPayDto wxPayDto = new WxPayDto();
            wxPayDto.setAppid(payConfiguration.getWx().getAppId());
            wxPayDto.setMch_id(payConfiguration.getWx().getMchId());
            wxPayDto.setSignKey(payConfiguration.getWx().getSignKey());
            wxPayDto.setTrade_type("APP");
            //测试0.01元 微信支付的单位 1分
            //wxPayDto.setTotal_fee(String.valueOf(1));
            wxPayDto.setTotal_fee(String.valueOf(totalPrice.multiply(new BigDecimal(100)).intValue()));
            wxPayDto.setBody("订单" + orderNum);
            wxPayDto.setOut_trade_no(orderNum);

            /**设置3分钟过期*/
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            Calendar expired = Calendar.getInstance();
            expired.set(Calendar.MINUTE, expired.get(Calendar.MINUTE) + 3);
            wxPayDto.setTime_expire(sdf.format(expired.getTime()));

            wxPayDto.setSpbill_create_ip("220.191.96.232");
            wxPayDto.setNotify_url(payConfiguration.getWx().getCallback() + "/api/open/wx_notify");
            PayResponse response = WxPayManage.mg.wxPay(wxPayDto);
            if (response.getStatus() == 1) {
                apiResponse.setStatus(900000);
                apiResponse.setMessage(response.getMessage());
                apiResponse.setParams(response.getParams());
                return apiResponse;
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new RuntimeException("微信支付订单创建失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException("微信支付订单创建失败！");
        }

    }


}
